package com.huluspace.datajdbc.dao;

import com.huluspace.datajdbc.model.User;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import org.springframework.jdbc.core.JdbcTemplate;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Optional;

@Repository // 表示该类是数据访问层（DAO），可被Spring扫描为Bean，并启用持久化异常转换机制
public class UserDao {

  // 注入JdbcTemplate，用于执行SQL语句
  private final JdbcTemplate jdbcTemplate;
  public UserDao(JdbcTemplate jdbcTemplate) {
    this.jdbcTemplate = jdbcTemplate;
  }

  // 保存用户
  public void save(User user) {
    String sql = "INSERT INTO users(username, password, enabled) VALUES (?, ?, ?)";
    jdbcTemplate.update(sql, user.getUsername(), user.getPassword(), user.isEnabled());
  }

  // 查找用户
  public Optional<User> findByUsername(String username) {
    String sql = "SELECT * FROM users WHERE username = ?";
    try {
      User user = jdbcTemplate.queryForObject(sql, new UserRowMapper(), username);
      return Optional.of(user);
    } catch (EmptyResultDataAccessException e) {
      return Optional.empty();
    }
  }

  // 列出所有用户
  public List<User> findAll() {
    String sql = "SELECT * FROM users";
    return jdbcTemplate.query(sql, new UserRowMapper());
  }

  // 用于将数据库结果映射为User对象
  private static class UserRowMapper implements RowMapper<User> {
    public User mapRow(ResultSet rs, int rowNum) throws SQLException {
      return new User(
          rs.getLong("id"),
          rs.getString("username"),
          rs.getString("password"),
          rs.getBoolean("enabled")
      );
    }
  }
}
